package pkg.drowne.org;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;



public class WaitPlayersDialog extends Activity implements OnClickListener, Runnable  {
	
	// Preference file
    public static final String PREF_FILE = "pf2";
    private SharedPreferences preferences;
	
    private boolean clientPlayer = false;
    
	private ListView lv;
	private Button startButton, testButton;
	private ArrayAdapter<String> arrayPlayers;
	
	private String[] PLAYERS = new String[] {"No players yet."};
	private String answer = "";
	
	private Double latDoubleValue, lonDoubleValue;
	
	private int idgame=-1, gameSessionID=-1;
	
	private boolean validLocations = false;
	
	private boolean isRefreshing = true;
	final Handler handler = new Handler();


	@Override
	public void onCreate(Bundle savedInstanceState) {
	  super.onCreate(savedInstanceState);
	  
	  setContentView(R.layout.waitstartgamedialog);
	  
	  registerViews();
	  setupOnClickListeners();
	  
	  loadPrefs();
	    
	  if (clientPlayer)	startButton.setVisibility(4);
	  
	  testButton.setVisibility(4);
	  
	  startButton.setEnabled(false);
	  
	  arrayPlayers = new ArrayAdapter<String>(this, R.layout.itemswaitplayersdialog, PLAYERS);
	  
      lv = (ListView) findViewById(R.id.list);
	  lv.setAdapter(arrayPlayers);
	  lv.setTextFilterEnabled(false);
	  
	  refreshPlayerList();
	  
	  this.run();
	  
	}
	
	
	private void loadPrefs() {
		
    	preferences  = getSharedPreferences(PREF_FILE, MODE_PRIVATE);
    	
    	clientPlayer  = preferences.getBoolean("clientPlayer", false);
    	idgame		  = preferences.getInt("idgame", -1);
    	gameSessionID = preferences.getInt("gameSessionID", -1);
        
	}
	
	
	private void registerViews() {
			
		 startButton = (Button) this.findViewById(R.id.start_game_button);
		 testButton  = (Button) this.findViewById(R.id.test_start_game_button);
		 
	}

	
	public void setupOnClickListeners() {
        
		startButton.setOnClickListener(this);
		testButton.setOnClickListener(this);
    }
    
	
    public void onClick(View V) {
    	
    	switch(V.getId()) {
    	
    	case R.id.start_game_button:
    		
    		// stop the player list updater
    		stopRefreshing();
    		
            new Thread(new Runnable() {
                public void run() {

                    Connection.setGamePhase(idgame, Utils.SPREAD);
                    Connection.autoAssignTeams(idgame);

                }

            }).start();
    		
    		Log.d("GAME ID: ", idgame + "");
    		
    		// Start the game
    		finish();
    		
    		break;
    		
    	}

    }


    public void refreshPlayerList() {

        new Thread(new Runnable() {
            public void run() {

                Looper.prepare();
                
                while(isRefreshing) {
                    
                    
                    // Check for game phase changes
                    if (Connection.getGamePhase(idgame) == Utils.SPREAD)
                        playerListHandler.sendEmptyMessage(2);
    
                    // Check for players list
                    answer = Connection.getPlayersList(idgame);
    
                    if (!answer.equals("EMPTY"))
                        playerListHandler.sendEmptyMessage(1);
                    
                    if(!clientPlayer) { 
                        
                        if(Connection.checkValidLocations(idgame) == 1)
                            validLocations = true;
                        else
                            validLocations = false;
                    
                    }
    
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                
                }

            }

        }).start();

    }
    
    private final Handler playerListHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			
			if (msg.what == 1) {
			    
			    String[] results = answer.split("\\|");
			    
                if(!clientPlayer) { 
                    
                    if(validLocations && results.length > 1)
                        startButton.setEnabled(true);
                    else
                        startButton.setEnabled(false);
                
                }
				

				PLAYERS = results;
				
				arrayPlayers = new ArrayAdapter<String>(getBaseContext(), R.layout.itemswaitplayersdialog, PLAYERS);
		
				lv.setAdapter(arrayPlayers);
				
			}
			
			
			if(msg.what == 2){
				
				Log.d("STOP", "Handler");
				stopRefreshing();
				finish();
				
			}
			
			
		}
	};

    public void stopRefreshing(){

        isRefreshing = false;
	   
    }
    
    public void finishActivity() {
    	this.finish();
    }


	@Override
	public void run() {
		
		// Acquire a reference to the system Location Manager
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
		
     // Define a listener that responds to location updates
        LocationListener locationListener = new LocationListener() {
            
            public void onLocationChanged(Location location) {

                latDoubleValue = location.getLatitude();
                lonDoubleValue = location.getLongitude();
                
                if(!clientPlayer) {
                    // if you created the game
                    // center the map on your first position and update 
                    // the center values on the database

                    if(latDoubleValue!=0 && lonDoubleValue!=0) {
                        // if we already have a clear position
                        // set the center position of the game

                        latDoubleValue = latDoubleValue * 1E6;
                        lonDoubleValue = lonDoubleValue * 1E6;
                        
                        int temp = Connection.setCenterPosition(idgame, latDoubleValue.intValue(), lonDoubleValue.intValue());
                        
                        Log.d("CENTER LAT", latDoubleValue+"");
                        Log.d("CENTER LON", lonDoubleValue+"");

                        preferences  = getSharedPreferences(PREF_FILE, MODE_PRIVATE);
                        preferences.edit().putInt("latDoubleValuePref", latDoubleValue.intValue()).commit();
                        preferences.edit().putInt("lonDoubleValuePref", lonDoubleValue.intValue()).commit();
                        
                        
                        if(temp != -1) {
                            Log.d("CENTER POSITION", "WAITSCREEN_OK");
                            
                            preferences.edit().putBoolean("centerIsSet", true).commit();
                            Connection.setPosition(gameSessionID, latDoubleValue.intValue(), lonDoubleValue.intValue());
                            
                        }
                        
                        
                        
                        
                    }
                } else {
                    // client
                    
                    if(latDoubleValue!=0 && lonDoubleValue!=0) {
                        
                        latDoubleValue = latDoubleValue * 1E6;
                        lonDoubleValue = lonDoubleValue * 1E6;
                        
                        int temp = Connection.setPosition(gameSessionID, latDoubleValue.intValue(), lonDoubleValue.intValue());
                        
                        if(temp != -1) { 
                            Log.d("WAITSCREEN PLAYER POSITION", "SAVED");
                            Log.d("PLAYER WAIT LAT", latDoubleValue+"");
                            Log.d("PLAYER WAIT LON", lonDoubleValue+"");
                            preferences  = getSharedPreferences(PREF_FILE, MODE_PRIVATE);
                            preferences.edit().putInt("latDoubleValue", latDoubleValue.intValue()).commit();
                            preferences.edit().putInt("lonDoubleValue", lonDoubleValue.intValue()).commit();
                        }
                        
                    }
                    
                }
                

            }

			@Override
			public void onProviderDisabled(String arg0) {
			    // do nothing
				
			}

			@Override
			public void onProviderEnabled(String arg0) {
				// do nothing
				
			}

			@Override
			public void onStatusChanged(String provider, int status,
					Bundle extras) {
			    // do nothing
				
			}
			
			
        };
        
        // Register the listener with the Location Manager to receive location
        // updates from the GPS and the cell towers
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 2, locationListener);
        //locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 2, locationListener);
        
	}

}
